package com.xzzz.irda.guardcat.server.alert.listener;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.xzzz.common.base.util.okhttp.HttpUtil;
import com.xzzz.irda.guardcat.core.pojo.Alert;
import com.xzzz.irda.guardcat.server.alert.AlertListener;
import com.xzzz.irda.guardcat.server.setting.AlertSetting;
import lombok.extern.slf4j.Slf4j;

/**
 * 企业微信机器人警告
 *
 * @author xzzz
 */
@Slf4j
public class AlertWechatRobotListener {

    public static final String TEST_ROBOT = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7664df38-0437-41a0-af72-7a8c9f92b25f";

    @AlertListener
    public void handle(Alert alert, AlertSetting alertSetting) {

        String[] robots = getRobots(alert, alertSetting);
        if (ArrayUtil.isEmpty(robots)) {
            return;
        }

        String prefix = alert.getLevel() == Alert.Level.INFO ? "通知" : "警告";
        String content = String.format(
            "{\n" +
            "  \"msgtype\":\"markdown\",\n" +
            "  \"markdown\":{\n" +
            "    \"content\":\"\n" +
            "      【重要】系统" + prefix + "\n" +
            "      >**" + prefix + "标题:%s** \n" +
            "      >\n" +
            "      >" + prefix + "时间：%s \n" +
            "      >" + prefix + "应用：`%s` \n" +
            "      >" + prefix + "节点：`%s`\n" +
            "      >追踪ID：%s\n" +
            "      >" + prefix + "ID：%s\n" +
            "      >\n" +
            "      >" + prefix + "内容：%s\n" +
            "      >\n" +
            "    \"\n" +
            "  }\n" +
            "}",
            alert.getTitle(),
            DateUtil.format(alert.getCreTime(),"yyyy-MM-dd HH:mm:ss"),
            alert.getAppName(),
            alert.getHostName(),
            alert.getTraceId(),
            alert.getId(),
            alert.getContent()
        );

        for (String robot : robots) {
            if (!robot.startsWith("https") || !robot.startsWith("http")) {
                log.warn("企业微信机器人格式错误: {}", robot);
                continue;
            }
            if (StrUtil.isNotBlank(robot)) {
                log.info("发布警告到企业微信机器人: {} > {}", alert.getTitle(), robot);
                try {
                    HttpUtil.post(robot, content);
                } catch (Exception e) {
                    log.error("发送微信机器人失败,警告: {}, 配置: {}, 异常: {}", alert.toString(), robot, e.getMessage());
                }
            }
        }
    }

    private String[] getRobots(Alert alert, AlertSetting alertSetting) {
        String[] robots = new String[0];
        if (alertSetting != null && StrUtil.isNotBlank(alertSetting.getWechatRobot())) {
            robots = alertSetting.getWechatRobot().split(",");
        }
        if (alert.getWechatRobot() != null) {
            robots = alert.getWechatRobot().split(",");
        }
        return robots;
    }
}
